import java.util.HashMap;
import java.util.Map;

public class Solution1123 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode lcaDeepestLeaves(TreeNode root) {
        Map<TreeNode,Integer> map=new HashMap<>();
        Map<TreeNode,TreeNode> father=new HashMap<>();
        dfs(null,root,0,map,father);
        int max=0;
        for (Integer value : map.values()) {
            if (value>max){
                max=value;
            }
        }
        TreeNode ans=null;
        for (Map.Entry<TreeNode, Integer> entry : map.entrySet()) {
            if (entry.getValue()==max){
                if (ans==null){
                    ans=entry.getKey();
                }else{
                    TreeNode treeNode=entry.getKey();
                    while (map.get(treeNode)>map.get(ans)){
                        treeNode=father.get(treeNode);
                    }
                    while (treeNode!=ans){
                        treeNode=father.get(treeNode);
                        ans=father.get(ans);
                    }
                }
            }
        }
        return ans;
    }

    private void dfs(TreeNode last,TreeNode root, int d, Map<TreeNode, Integer> map,Map<TreeNode,TreeNode> father) {
        if (root==null){
            return;
        }
        father.put(root,last);
        map.put(root,d);
        dfs(root,root.left,d+1,map,father);
        dfs(root,root.right,d+1,map,father);
    }

    public static void main(String[] args) {
        System.out.println(new Solution1123().lcaDeepestLeaves(new TreeNode(3,new TreeNode(5,new TreeNode(6),new TreeNode(2,new TreeNode(7),new TreeNode(4))),new TreeNode(1,new TreeNode(0),new TreeNode(8)))).val);
    }
}
